package cn.chenxiejia;

import java.io.*;

/***
 * @program: maven
 * @ClassName: TestFile7
 * @Description: 按缓冲区分割
 * @Author: chenxiejia
 * @Date: 2022/1/18 22:07
 * @version : V1.0
 */
public class File8 {
    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("E:/aa.txt");
        File file1 = new File("D:/aa.txt");
        //分配缓冲区大小
        int a = 1024 * 6;
        try (FileInputStream raf = new FileInputStream(file)) {
            int len = 0;
            int i = 0;
            byte[] buf = new byte[a];

            while ((len = raf.read(buf)) != -1) {
                i++;
                //自动分割文件
                FileOutputStream raf1 = new FileOutputStream(new File("D:/aa" + i + ".txt"));
                raf1.write(buf, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        int j = 0;
        //追加写入
        FileOutputStream fos = new FileOutputStream(file1, true);
        int num = 0;
        //System.out.println((file.length() / a) + 1);
        //分析分割成了几个文件
        if (file.length() % a != 0) {
            num = (int) ((file.length() / a) + 1);
        }
        //合并文件
        for (int i = 1; i <= num; i++) {
            ++j;
            try (FileInputStream fis = new FileInputStream(new File("D:/aa" + j + ".txt"))) {
                fos.write(fis.readAllBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
